﻿package com.kuanter.kuanterauto.adapter;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.LincensePlateNumberActivity;
import com.kuanter.kuanterauto.activity.MyCarActivity;
import com.kuanter.kuanterauto.activity.XgcxActivity;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.entity.VehicleInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.utils.BrandStrToIconUtil;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtil;

public class CarListAdapter extends BaseAdapter {
	public static List<VehicleInfo> vehicleInfos;
	private Activity fromActivity;
	private TextView car_brand_and_model_tv;
	private ImageView brand_logo_iv;
	private TextView licensePlateNumber_tv;
	private TextView car_annual_audit_deadline_tv;
	private TextView car_insurance_deadline_tv;
	private Intent intent = new Intent();
	private View choose_brand_and_car_model_goto;
	private View choose_license_plate_number_goto;
	private View annual_audit_deadline_goto;
	private View insurance_deadline_goto;
	private Button delete_car;
	private int userId;
	private int position;
	private ProgressDialog progressDialog;
	public static int changeIndex;

	public CarListAdapter(List<VehicleInfo> vehicleInfos, Activity fromActivity) {
		this.vehicleInfos = vehicleInfos;
		this.fromActivity = fromActivity;
		userId = SharePrefenceUtil.getUserID(fromActivity);
	}

	public CarListAdapter addDataItem(VehicleInfo vehicleInfo) {
		vehicleInfos.add(vehicleInfo);
		ProApplication.getInstance().setList_vehicleInfo(vehicleInfos);
		if (vehicleInfos.size() > 1) {
			delete_car.setVisibility(View.VISIBLE);
		}else {
			delete_car.setVisibility(View.GONE);
		}
		this.notifyDataSetChanged();
		return this;
	}

	public CarListAdapter deleteDataItem(int position) {
		vehicleInfos.remove(position);
		ProApplication.getInstance().setList_vehicleInfo(vehicleInfos);
		if (vehicleInfos.size() > 1) {
			delete_car.setVisibility(View.VISIBLE);
		} else 
			delete_car.setVisibility(View.GONE);
		this.notifyDataSetChanged();
		return this;
	}
	
	public CarListAdapter updateDataItem(int position,VehicleInfo vehicleInfo) {
		this.vehicleInfos.get(position).setId(vehicleInfo.getId());
		if(null == vehicleInfo.getVehicleBrand()||"".equals(vehicleInfo.getVehicleBrand())){
//			this.vehicleInfos.get(position).setVehicleBrand("暂无");
		}else
			this.vehicleInfos.get(position).setVehicleBrand(vehicleInfo.getVehicleBrand());
		if(null == vehicleInfo.getVehicleModels()||"".equals(vehicleInfo.getVehicleModels())){
//			this.vehicleInfos.get(position).setVehicleModels("暂无");
		}else 
			this.vehicleInfos.get(position).setVehicleModels(vehicleInfo.getVehicleModels());
		if(null == vehicleInfo.getLicensePlateNumber()||"".equals(vehicleInfo.getLicensePlateNumber())){
//			this.vehicleInfos.get(position).setLicensePlateNumber("暂无");
		}else 
			this.vehicleInfos.get(position).setLicensePlateNumber(vehicleInfo.getLicensePlateNumber());
		if(null == vehicleInfo.getInspectionExpireTime()||"".equals(vehicleInfo.getInspectionExpireTime())){
//			this.vehicleInfos.get(position).setInspectionExpireTime("暂无");
		}else 
			this.vehicleInfos.get(position).setInspectionExpireTime(vehicleInfo.getInspectionExpireTime());
		if(null == vehicleInfo.getInsuranceEndTime()||"".equals(vehicleInfo.getInsuranceEndTime())){
//			this.vehicleInfos.get(position).setInsuranceEndTime("暂无");
		}else 
			this.vehicleInfos.get(position).setInsuranceEndTime(vehicleInfo.getInsuranceEndTime());
		this.vehicleInfos.get(position).setModification(true);
		this.notifyDataSetChanged();
		ProApplication.getInstance().setList_vehicleInfo(vehicleInfos);
		if (vehicleInfos.size() > 1) {
			delete_car.setVisibility(View.VISIBLE);
		} else 
			delete_car.setVisibility(View.GONE);
		return this;
	}
	

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return vehicleInfos.size();
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return vehicleInfos.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View view = null;
		if (null == convertView) {
			view = View.inflate(fromActivity, R.layout.car_listview_item, null);
		} else {
			view = convertView;
		}
		annual_audit_deadline_goto = view
				.findViewById(R.id.annual_audit_deadline_goto);
		insurance_deadline_goto = view
				.findViewById(R.id.insurance_deadline_goto);

		// 删除车辆
		delete_car = (Button) view.findViewById(R.id.delete_car);
		if (vehicleInfos.size() > 1) {
			delete_car.setVisibility(View.VISIBLE);
		}else{
			delete_car.setVisibility(View.GONE);
		}

		choose_brand_and_car_model_goto = (LinearLayout) view
				.findViewById(R.id.choose_brand_and_car_model_goto);
		choose_license_plate_number_goto = view
				.findViewById(R.id.choose_license_plate_number_goto);
		car_brand_and_model_tv = (TextView) view
				.findViewById(R.id.car_brand_and_model_tv);
		car_brand_and_model_tv.setText(vehicleInfos.get(position)
				.getVehicleBrand()
				+ "  "
				+ vehicleInfos.get(position).getVehicleModels());
		brand_logo_iv = (ImageView) view.findViewById(R.id.brand_logo_iv);
		if(null == vehicleInfos.get(position).getVehicleBrand()){
			
		}else 
			Log.i("ccc", vehicleInfos + "---" + vehicleInfos.get(position) + "-------" + vehicleInfos.get(position).getVehicleBrand());
			brand_logo_iv.setImageResource(new BrandStrToIconUtil().getBrandIcon(vehicleInfos.get(position).getVehicleBrand()));
		licensePlateNumber_tv = (TextView) view
				.findViewById(R.id.licensePlateNumber_tv);
		if(null == vehicleInfos.get(position).getLicensePlateNumber()){
			
		}else 
			licensePlateNumber_tv.setText(vehicleInfos.get(position).getLicensePlateNumber());
		// car_annual_audit_deadline_tv
		car_annual_audit_deadline_tv = (TextView) view
				.findViewById(R.id.car_annual_audit_deadline_tv);
		if(vehicleInfos.get(position).getInspectionExpireTime() != null && !vehicleInfos.get(position).getInspectionExpireTime().equals("null")) {
			car_annual_audit_deadline_tv.setText(vehicleInfos.get(position).getInspectionExpireTime());
		} else {
			car_annual_audit_deadline_tv.setText("");
		}
		car_insurance_deadline_tv = (TextView) view
				.findViewById(R.id.car_insurance_deadline_tv);
		
		if(vehicleInfos.get(position).getInsuranceEndTime() != null && !vehicleInfos.get(position).getInsuranceEndTime().equals("null")) {
			car_insurance_deadline_tv.setText(vehicleInfos.get(position)
					.getInsuranceEndTime());
		} else {
			car_insurance_deadline_tv.setText("");
		}
		
		choose_brand_and_car_model_goto
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						intent.setClass(fromActivity, XgcxActivity.class);
						intent.putExtra("position", position);
						fromActivity.startActivityForResult(intent,
								MyCarActivity.CHOOSE_CAR_BRAND_MODEL);
					}
				});
		choose_license_plate_number_goto
				.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						intent = new Intent(fromActivity,
								LincensePlateNumberActivity.class);
						intent.putExtra("position", position);
						if(null != vehicleInfos.get(position).getVehicleBrand()&&!"".equals(vehicleInfos.get(position).getVehicleBrand())){
							intent.putExtra("LicensePlateNumber", vehicleInfos.get(position).getLicensePlateNumber());
						}
						fromActivity.startActivityForResult(intent,
								MyCarActivity.CHOOSE_LINCENSE_PLATE_NUMBER);
					}
				});

		TextView car_brand_and_model_tv = (TextView) view
				.findViewById(R.id.car_brand_and_model_tv);

		annual_audit_deadline_goto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				flag = ANNUAL_AUDIT_DEADLINE;
				fromActivity.showDialog(position);
				changeIndex = position;
			}
		});

		insurance_deadline_goto.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				flag = CAR_INSURANCE_DEADLINE;
				fromActivity.showDialog(position);
				changeIndex = position;
			}
		});

		delete_car.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder builder = new AlertDialog.Builder(
						fromActivity);
				builder.setTitle("删除该车吗？");
				builder.setMessage(vehicleInfos.get(position).getVehicleBrand()
						+ "  " + vehicleInfos.get(position).getVehicleModels());
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface arg0, int arg1) {
								List<NameValuePair> params1 = new ArrayList<NameValuePair>();
								params1.add(new BasicNameValuePair("userId",
										userId + ""));
								Log.i("aaa", position  + "--position---------" + vehicleInfos.get(position).getId() + "---id");
								params1.add(new BasicNameValuePair("id",
										vehicleInfos.get(position).getId()));
								new DataLoader(fromActivity).DisplayData(
										MainConstants.HOST_test
												+ HttpConfigAPI.DELETE_VEHICLE,
										params1, handler, "", false);
								showProgress("加载中");
								CarListAdapter.this.position = position;
							}
						});

				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface arg0, int arg1) {
							}
						});

				builder.create().show();
			}
		});

		return view;
	}

	/**
	 * 显示异步上传时的等待进度框
	 * 
	 * @param message
	 *            进度框内容文字
	 */
	private void showProgress(String message) {
		if(progressDialog == null) {
			progressDialog = new ProgressDialog(fromActivity);
			progressDialog.setCanceledOnTouchOutside(false);
//			progressDialog.setCancelable(false);
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.setMessage(message);
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					fromActivity.finish();
				}
			});
			progressDialog.show();
		} else if(!progressDialog.isShowing()) {
			progressDialog.setCanceledOnTouchOutside(false);
//			progressDialog.setCancelable(false);
			progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			progressDialog.setMessage(message);
			progressDialog.show();
			progressDialog.setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) {
					fromActivity.finish();
				}
			});
		}
	}
	
	/**
	 * 结束进度框
	 * 
	 * @param progress
	 */
	protected void finishProgress() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
	public static final int ANNUAL_AUDIT_DEADLINE = 2;
	public static final int CHOOSE_DATE = 0;
	public static int flag;

	public static final int CHOOSE_BRAND = 1;

	public static final int CAR_INSURANCE_DEADLINE = 3;
	private ProApplication application;

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case HttpTask.RESULT_OK:
				String result = (String) msg.obj;
				if (!result.equals("网络连接错误")) {
					try {
						if (StringUtil.isSuccess(result)) {// 判断返回数据中 status
							VehicleInfo vehicleInfo = vehicleInfos.get(position);
							CarListAdapter.this.deleteDataItem(position);
							finishProgress();
						} else {
							finishProgress();
						}
					} catch (JSONException e) {
						Toast.makeText(fromActivity, "登录失败", 0).show();
						e.printStackTrace();
						finishProgress();
					}
				} else {
					Toast.makeText(fromActivity, "登录失败,网络错误!", 0).show();
					finishProgress();
				}
				break;
			case HttpTask.RESULT_ERROR:
				Toast.makeText(fromActivity, "网络错误!", 0).show();
				finishProgress();
				break;
			}
		}
	};

}
